﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace FreedomX2.Core.IO
{
    public class ConfigDynamic
    {
        public static ConfigDynamic Pub = new ConfigDynamic();
        private XmlDocument Doc = new XmlDocument();
        private AppDomain Ad = AppDomain.CurrentDomain;
        public ConfigDynamic()
        {
            Doc.Load(Ad.SetupInformation.ConfigurationFile);
        }
        /// <summary>
        /// 重新加载配置文件(仅在需要时)
        /// </summary>
        public void LoadAppConfig()
        {
            Doc.Load(Ad.SetupInformation.ConfigurationFile);
        }
        /// <summary>
        /// 设置AppSettings的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="newValue"></param>
        public void SetAppValue(string key, string newValue)
        {
            Doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value = newValue;
        }
        /// <summary>
        /// 设置路径元素的值
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyName"></param>
        /// <param name="key"></param>
        /// <param name="valueName"></param>
        /// <param name="newValue"></param>
        public void SetAppValue(string path, string keyName, string key, string valueName, string newValue)
        {
            try
            {
                Doc.SelectSingleNode(path + "[@" + keyName + "='" + key + "']").Attributes[valueName].Value = newValue;
            }
            catch { }
        }
        /// <summary>
        /// 保存配置
        /// </summary>
        public void SaveAppConfig()
        {
            Doc.Save(Ad.SetupInformation.ConfigurationFile);
            Doc.Load(Ad.SetupInformation.ConfigurationFile);
        }
        /// <summary>
        /// 获得路径值
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyName"></param>
        /// <param name="key"></param>
        /// <param name="valueName"></param>
        /// <returns></returns>
        public string GetAppValueByName(string path, string keyName, string key, string valueName)
        {
            try
            {
                return Doc.SelectSingleNode(path + "[@" + keyName + "='" + key + "']").Attributes[valueName].Value;
            }
            catch { }
            return "";
        }
        /// <summary>
        /// 获得AppSettings内的值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetAppValue(string key)
        {
            return Doc.SelectSingleNode("/configuration/appSettings/add[@key='" + key + "']").Attributes["value"].Value;
        }
    }
}
